import type { Request, Response } from 'express';

import { z } from 'zod';

import { AppModel } from '../../../models/app';
import Resp from '../../../utils/response';
import { deleteAppDirectory } from '../utils';

// 参数校验规则
export const validator = z.object({
  ID: z
    .string({
      invalid_type_error: '应用ID必须是字符串',
      required_error: '应用ID不能为空',
    })
    .min(1, '应用ID不能为空'),
});

// 删除应用API
export const api = async (req: Request, res: Response): Promise<Response> => {
  try {
    const { ID } = req.params as z.infer<typeof validator>;

    // 检查应用是否存在并删除
    const result = await AppModel.findByIdAndDelete(ID);
    if (!result) {
      return Resp.error(res, 404, '应用不存在');
    }
    // 删除文件夹
    await deleteAppDirectory(ID);

    return Resp.success(res, null, '应用删除成功');
  } catch (error) {
    console.error(error);
    return Resp.catch(res, error);
  }
};
